'use strict'

import { app, protocol, BrowserWindow, dialog, ipcMain, globalShortcut, Tray, Menu } from 'electron'
import path from 'path'
import fs from 'fs'
import axios from 'axios'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import nodePath from 'path'
import { winURL } from './utils/StaticPath'
import { checkUpdate } from './update.js'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
const preload = nodePath.join(__dirname, './preload.js');

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true, stream: true } }
])
let win = null;
let tray = null
let blinkInterval = null; // 定时器，用于闪烁

async function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    // width: 800,
    // height: 600,
    width: 320,
    height: 450,
    frame: false,
    autoHideMenuBar: true, // 隐藏菜单栏
    webPreferences: {

      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      // nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      // contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      webSecurity: false, //关闭安全策略, 解决跨域问题

      nodeIntegration: true,
      contextIsolation: false,
      devTools: true,
      preload,
    }
  })

  win.on('focus', () => {
    stopBlink();
  });


  globalShortcut.register('CommandOrControl+Shift+i', () => {
    const isOpen = win.webContents.isDevToolsOpened();
    // 根据当前控制台的状态选择关闭/打开控制台
    if (isOpen) {
      // 关闭控制台
      win.webContents.closeDevTools();
    } else {
      // 打开控制台
      win.webContents.openDevTools();
    }
  })

  // win.webContents.openDevTools()
  ipcMain.on("maximize-window", () => {
    if (win.isMaximized()) {
      win.restore(); // 如果窗口已经最大化，则恢复原始大小
    } else {
      win.maximize(); // 否则，最大化窗口
    }
  });
  // 最小化
  ipcMain.on("minimize-window", () => {
    win.minimize();
  });

  // 关闭窗口
  ipcMain.on("close-window", () => {
    win.destroy();
  });

  // 最小化
  ipcMain.on("hide-window", () => {
    win.hide();
  });

  //检查更新
  ipcMain.on("check-update", () => {
    checkUpdate(win, ipcMain);
  });

  ipcMain.on("reset-window", (event, width, height, center) => {
    if (typeof width !== "number" || typeof height !== "number") {
      console.error("Invalid width or height");
    }
    win.setContentSize(width, height);
    if (center) {
      win.center()
    }
  });

  ipcMain.on("center-window", () => {
    win.center()
  });

  ipcMain.on("start-blink", () => {
    startBlink()
  });

  ipcMain.on("stop-blink", () => {
    stopBlink()
  });

  ipcMain.on('start-download', async (event, { url, savePath, file }) => {
    console.log("🚀🚀🚀 ~ ipcMain.on ~ url:", url,savePath,'url---------------------savePath')
    try {
      // 弹出目录选择对话框
      const { filePath } = await dialog.showSaveDialog({
        title: '保存文件',
        defaultPath: path.join(app.getPath('downloads'), savePath || 'download-file'),
        defaultPath: file.name,
        buttonLabel: '保存',
        filters: [
          { name: 'All Files', extensions: ['*'] }
        ]
      })

      if (!filePath) return { status: 'cancelled' }


      // 创建目录（如果不存在）
      const dir = path.dirname(filePath)
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true })
      }

      // 下载文件
      const response = await axios({
        url,
        method: 'GET',
        responseType: 'stream',
        onDownloadProgress: (progressEvent) => {
          const progress = progressEvent.loaded / progressEvent.total
          // BrowserWindow.getAllWindows().webContents.send('download-progress', progress)
        }
      })

      // 写入文件
      const writer = fs.createWriteStream(filePath)
      response.data.pipe(writer)
      writer.on('finish', () => {
        event.sender.send('download-complete', filePath)
      })

      writer.on('error', (err) => {
        event.sender.send('download-error', err.message)
      })

    } catch (err) {
      console.log("🚀🚀🚀 ~ ipcMain.on ~ err:", err)
      // event.sender.send('download-error', err.message)
    }
  })


  let childWin = null;
  let cidArray = [];
  ipcMain.on('open-win', (event, arg) => {
    let cidJson = { id: null, url: '' }
    let data = cidArray.filter((currentValue) => {
      if (currentValue.url === arg.url) {
        return currentValue
      }
    })
    if (data.length > 0) {
      //获取当前窗口
      let currentWindow = BrowserWindow.fromId(data[0].id)
      //聚焦窗口
      currentWindow.focus();
      if (arg.productId) {
        currentWindow.loadURL(winURL + `#${arg.url}${arg.productId ? '?productId=' + arg.productId : ''}`)
      }
    } else {
      //获取主窗口ID
      let parentID = event.sender.id
      //创建窗口
      childWin = new BrowserWindow({
        width: arg.width || 842,
        height: arg.height || 595,
        //width 和 height 将设置为 web 页面的尺寸(译注: 不包含边框), 这意味着窗口的实际尺寸将包括窗口边框的大小，稍微会大一点。 
        useContentSize: true,
        //自动隐藏菜单栏，除非按了Alt键。
        autoHideMenuBar: true,
        //窗口大小是否可调整
        resizable: arg.resizable || false,
        //窗口的最小高度
        minWidth: arg.minWidth || 842,
        show: arg.show || false,
        //窗口透明度
        opacity: arg.opacity || 1.0,
        //当前窗口的父窗口ID
        parent: parentID,
        frame: 1,
        webPreferences: {
          nodeIntegration: true,
          webSecurity: false,
          //使用webview标签 必须开启
          webviewTag: arg.webview || false,
          // 如果是开发模式可以使用devTools
          devTools: process.env.NODE_ENV === 'development',
          // 在macos中启用橡皮动画
          scrollBounce: process.platform === 'darwin',
          // 临时修复打开新窗口报错
          contextIsolation: false
        }
      })
      console.log(winURL + `#${arg.url}${arg.productId ? '?productId=' + arg.productId : ''}`)
      childWin.loadURL(winURL + `#${arg.url}${arg.productId ? '?productId=' + arg.productId : ''}`)
      cidJson.id = childWin.id
      cidJson.url = arg.url
      cidArray.push(cidJson)
      if (process.env.NODE_ENV === 'development') childWin.webContents.openDevTools();
      childWin.webContents.once('dom-ready', () => {
        childWin.show()
        childWin.webContents.send('send-data', arg.sendData)
        if (arg.IsPay) {
          // 检查支付时候自动关闭小窗口
          const testUrl = setInterval(() => {
            const Url = childWin.webContents.getURL()
            if (Url.includes(arg.PayUrl)) {
              childWin.close()
            }
          }, 1200)
          childWin.on('close', () => {
            clearInterval(testUrl)
          })
        }
      })
      childWin.on('closed', () => {
        childWin = null
        let index = cidArray.indexOf(cidJson)
        if (index > -1) {
          cidArray.splice(index, 1);
        }
      })
    }
    childWin.on('maximize', () => {
      if (cidJson.id != null) {
        BrowserWindow.fromId(cidJson.id).webContents.send("w-max", true)
      }
    })
    childWin.on('unmaximize', () => {
      if (cidJson.id != null) {
        BrowserWindow.fromId(cidJson.id).webContents.send("w-max", false)
      }
    })
  })

  // 检查更新
  // checkUpdate(win, ipcMain);
  // 关闭工具栏
  win.setMenu(null)

  ipcMain.on('tray-message-received', () => {
    // if (mainWindow && !mainWindow.isFocused() && !mainWindow.isMinimized()) {
    // if (win && !win.isFocused()) {
    // 如果窗口未聚焦且未最小化，则闪烁窗口
    win.flashFrame(true);
    startBlink()
    // }
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
}

async function initTrayIcon() {
  // const iconPath = nodePath.join(__dirname, '../icon.png'); // 读取 public 目录下的 icon.ico


  let iconPath;
  let iconBlink;
  if (app.isPackaged) {
    // 打包后的环境
    iconPath = nodePath.join(__dirname, './icon.png');
    iconBlink = nodePath.join(__dirname, './icon_tran.png');
  } else {
    // 开发环境
    iconPath = nodePath.join(__dirname, '../public/icon.png');
    iconBlink = nodePath.join(__dirname, '../public/icon_tran.png');
  }


  tray = new Tray(iconPath);
  const contextMenu = Menu.buildFromTemplate([
    { label: '打开应用', click: () => win.show() },
    { label: '最小化', click: () => win.minimize() },
    { type: 'separator' },
    { label: '退出', click: () => win.destroy() }
  ]);

  tray.setToolTip('Chatup');
  tray.setContextMenu(contextMenu);

  tray.on('click', () => { stopBlink(); win.show() }); // 单击托盘图标显示主窗口
}

// **启动托盘图标闪烁**
function startBlink() {

  let iconPath;
  let iconBlink;
  if (app.isPackaged) {
    // 打包后的环境
    iconPath = nodePath.join(__dirname, './icon.png');
    iconBlink = nodePath.join(__dirname, './icon_tran.png');
  } else {
    // 开发环境
    iconPath = nodePath.join(__dirname, '../public/icon.png');
    iconBlink = nodePath.join(__dirname, '../public/icon_tran.png');
  }

  let isBlink = false;

  if (blinkInterval) return; // 防止重复调用

  blinkInterval = setInterval(() => {
    if (!tray) {
      console.error("Tray is not initialized.");
      return;
    }

    tray.setImage(isBlink ? iconBlink : iconPath);
    isBlink = !isBlink;
  }, 500); // 每 500ms 切换图标
}

// **停止闪烁**
function stopBlink() {
  if (!tray) {
    console.error("Tray is not initialized.");
    return;
  }

  if (blinkInterval) {
    clearInterval(blinkInterval);
    blinkInterval = null;
  }
  let iconPath;
  let iconBlink;
  if (app.isPackaged) {
    // 打包后的环境
    iconPath = nodePath.join(__dirname, './icon.png');
    iconBlink = nodePath.join(__dirname, './icon_tran.png');
  } else {
    // 开发环境
    iconPath = nodePath.join(__dirname, '../public/icon.png');
    iconBlink = nodePath.join(__dirname, '../public/icon_tran.png');
  }


  tray.setImage(iconPath); // 还原默认图标
}


// **防止所有窗口关闭时退出**
// app.on('window-all-closed', (event) => {
//   event.preventDefault();
//   mainWindow.hide();
// });
// 添加剪贴板IPC处理
ipcMain.handle('copy-file-to-clipboard', (event, filePath) => {
  const platform = process.platform; // ✅ 正确获取平台
  try {
    if (platform === 'win32') {
      const buffer = Buffer.from(filePath + '\0', 'utf16le');
      clipboard.writeBuffer('FileNameW', buffer);
    } else if (platform === 'darwin') {
      const fileURL = `file://${encodeURIComponent(filePath)}`;
      clipboard.write({ text: fileURL, bookmark: fileURL });
    } else if (platform === 'linux') {
      clipboard.writeText(`file://${filePath}`);
    } else {
      throw new Error('Unsupported platform');
    }
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

//切换窗口
ipcMain.on('share-to-main', () => {
  win.show();
  win.loadURL(winURL + `#/home/chat?share=1`)
  // secondWindow.show();
});
// **应用退出时清理托盘**
app.on('before-quit', () => {
  if (tray) tray.destroy();
});

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  // if (isDevelopment && !process.env.IS_TEST) {
  //   // Install Vue Devtools
  //   try {
  //     await installExtension(VUEJS_DEVTOOLS)
  //   } catch (e) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  createWindow()
  initTrayIcon()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
